package com.lhb.aicodemother.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.lhb.aicodemother.exception.ErrorCode;
import com.lhb.aicodemother.exception.ThrowUtils;
import com.lhb.aicodemother.manager.CosManager;
import com.lhb.aicodemother.service.ScreenshotService;
import com.lhb.aicodemother.utils.WebScreenshotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
public class ScreenshotServiceImpl implements ScreenshotService {
    @Resource
    private CosManager cosManager;

    @Override
    public String generateAndUploadScreenshot(String webUrl) {
        ThrowUtils.throwIf(StrUtil.isBlank(webUrl), ErrorCode.PARAMS_ERROR,"网页URL不能为空");
        log.info("开始生成网页截图，URL：{}",webUrl);
        // 1.生成本地截图
        String localScreenshotPath = WebScreenshotUtils.saveWebPageScreenshot(webUrl);
        ThrowUtils.throwIf(StrUtil.isBlank(localScreenshotPath), ErrorCode.OPERATION_ERROR,"本地截图生成失败");
        try{
            // 2.上传到对象存储
            String url = uploadScreenshot(localScreenshotPath);
            ThrowUtils.throwIf(StrUtil.isBlank(url),ErrorCode.OPERATION_ERROR,"截图上传失败");
            log.info("网页截图生成并上传成功：{} -> {}",webUrl,url);
            return url;
        }finally {
            // 3.清理本地文件
            cleanLocalFile(localScreenshotPath);
        }
    }

    /*
    * 上传截图到对象存储
    * */
    private String uploadScreenshot(String localScreenshotPath){
        if(StrUtil.isBlank(localScreenshotPath)){
            return null;
        }
        File file = new File(localScreenshotPath);
        if(!file.exists()){
            log.error("截图文件不存在，{}",localScreenshotPath);
            return null;
        }
        // 生成COS键
        String fileName = UUID.randomUUID().toString().substring(0,8) + "_compressed.jpg";
        String cosKey = generateScreenshotKey(fileName);
        return cosManager.uploadFile(cosKey,file);
    }

    /*
    * 生成截图的对象存储键
    * */
    private String generateScreenshotKey(String fileName){
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return String.format("/screenshot/%s/%s",datePath,fileName);
    }

    /*
    * 清理本地文件
    * */
    private void cleanLocalFile(String localFilePath){
        File file = new File(localFilePath);
        if(file.exists()){
            File parentFile = file.getParentFile();
            FileUtil.del(parentFile);
            log.info("本地截图文件已清理：{}",localFilePath);
        }
    }
}
